package com.kma.ncpractice2013.dao;

import com.kma.ncpractice2013.model.UserGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import org.springframework.jdbc.core.RowMapper;

/**
 *
 * @author Illya
 */
public class UserGroupDAO extends DAO<UserGroup>
{
    
    public void create(UserGroup userGroup)
    {
        String sql = "INSERT INTO USER_GROUPS(ID,DESCRIPTION,DISCOUNT) VALUES (?,?,?)";
        jdbcTemplate.update(sql, new Object[]{userGroup.getId(),userGroup.getDescription(),
            userGroup.getDiscount()});
    }

    public void update(UserGroup userGroup)
    {
        String sql = "UPDATE USER_GROUPS SET DESCRIPTION = ?,DISCOUNT = ? WHERE ID = ?";
        jdbcTemplate.update(sql, new Object[]{userGroup.getDescription(),userGroup.getDiscount()});
    }

    public UserGroup getById(int id)
    {
        List<UserGroup> userGroupList;
        String sql = "SELECT * FROM USER_GROUPS WHERE ID = " + id;
        userGroupList = jdbcTemplate.query(sql, new UserGroupRowMapper());
        return userGroupList.get(0);
    }

    public Collection<UserGroup> getAll()
    {
        String sql = "SELECT  * FROM USER_GROUPS ";
	    return jdbcTemplate.query(sql, new UserGroupRowMapper());
    }

    public void deleteById(int id)
    {
        String sql = "DELETE FROM USER_GROUPS WHERE ID = " + id;
        jdbcTemplate.update(sql);
    }
    
    private static final class UserGroupRowMapper implements RowMapper
    {
        @Override
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException
        {
            UserGroup userGroup = new UserGroup();
            userGroup.setId(rs.getInt("id"));
            userGroup.setDescription(rs.getString("description"));
            userGroup.setDiscount(rs.getInt("discount"));
            // set relatedUsers?
            return userGroup;
        }
    }
}
